package com.bj58.groupbuy.action.controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.bsp.Provider;
import com.bj58.bsp.user.bean.UserInfo;
import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.DBHostPwd;
import com.bj58.groupbuy.action.model.DBPriviledge;
import com.bj58.groupbuy.action.model.DBUser;
import com.bj58.groupbuy.action.model.IRSubMailVo;
import com.bj58.groupbuy.action.model.Menu;
import com.bj58.groupbuy.action.model.OperMenu;
import com.bj58.groupbuy.action.model.Role;
import com.bj58.groupbuy.action.model.RolePriviledge;
import com.bj58.groupbuy.action.model.SysNotice;
import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.model.UserRole;
import com.bj58.groupbuy.action.model.UserSubMailVo;
import com.bj58.groupbuy.action.service.DBService;
import com.bj58.groupbuy.action.service.IRSubMailService;
import com.bj58.groupbuy.action.service.MenuService;
import com.bj58.groupbuy.action.service.NoticeService;
import com.bj58.groupbuy.action.service.RoleManagerService;
import com.bj58.groupbuy.action.service.RolePriviledgeService;
import com.bj58.groupbuy.action.service.UserManagerService;
import com.bj58.groupbuy.action.service.UserOperService;
import com.bj58.groupbuy.action.service.UserRoleService;
import com.bj58.groupbuy.action.service.UserSubMailService;
import com.bj58.groupbuy.action.util.DateUtil;
import com.bj58.groupbuy.action.util.MyStore;
import com.bj58.groupbuy.action.util.PatternUtil;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;

/**
 * 系统管理
 * @author HL
 *
 */
public class ManagerController extends MvcController {
	private UserManagerService userManagerService = ServiceLocator.get(UserManagerService.class);
	private DBService dbService = ServiceLocator.get(DBService.class);
	private RolePriviledgeService rolePriviledgeService = ServiceLocator.get(RolePriviledgeService.class);
	private UserRoleService userRoleService = ServiceLocator.get(UserRoleService.class);
	private RoleManagerService roleManagerService = ServiceLocator.get(RoleManagerService.class);
	private MenuService menuService = ServiceLocator.get(MenuService.class);
	private SomePublicUtil spu = new SomePublicUtil();
	private IRSubMailService iRSubMailService = ServiceLocator.get(IRSubMailService.class);
	private UserSubMailService UserDownService = ServiceLocator.get(UserSubMailService.class);
	private UserOperService UserOperService = ServiceLocator.get(UserOperService.class);
	private NoticeService NoticeService = ServiceLocator.get(NoticeService.class);

	@Path("")
	@GET
	@POST
	public ActionResult login() {
		return ActionResult.view("default/login");
	}

	/**
	 * 用户验证
	 * 
	 * @return
	 */
	@Path("login")
	@POST
	@GET
	public ActionResult loginCheck() {
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		Model model = beat.getModel();

		try {
			// 验证用户账号密码
			String userName = request.getParameter("username");
			String pwd = request.getParameter("pwd");

			if (null == userName || "".equals(userName) || null == pwd|| "".equals(pwd)) {
				return ActionResult.view("default/login");
			}

			 //用户名输入校验
			if(!PatternUtil.checkUserName(userName)){
				model.add("message","输入非法信息!只允许输入中文、英文、数字、下划线");
				return ActionResult.view("default/login");
			}

			UserInfo ui = new UserInfo();
			
			if("fortv".equals(userName)  && "Ecdata123123".equals(pwd)){//实时数据TV专用账户  不走OA校验
				ui.setUserName("fortv");
				log.info(" fortv login");
			}else{
				try {
					 ui = Provider.getUserService().getUserByPWD(userName,pwd);//OA用户
					// ui.setUserName("houzuoxin");
				} catch (Exception e) {
					e.printStackTrace();
					model.add("message", "OA账户校验失败，请确认账户密码正确！");
					return ActionResult.view("default/login");
				}

				if (null == ui || "".equals(ui.getUserName())
						|| null == ui.getUserName()) {
					model.add("message", "OA账户校验失败，请确认账户密码正确！");
					return ActionResult.view("default/login");
				}
			}
			

			/**
			 * 如果用户未进行OA账户校验绑定，则需将OA账户与原BI账户绑定校验
			 * 步骤：1.先匹配OA用户名和原BI系统用户名，如果一致则直接绑定
			 * 2.如果两个用户名不一致，则需输入原BI系统账户密码进行确认，再将BI系统中的用户名更新为OA用户名，并更改绑定状态
			 */
			User user = userManagerService.getUserByName(ui.getUserName());// bi系统用户
			if (null == user || "".equals(user.getUsername())) {
				model.add("message","您还未开通本系统权限，请点开下方红色链接查看申请流程。");
				return ActionResult.view("default/login");
			}

			String func = userManagerService.getFunctionsByUser(user);
			// 用户信息写入cookie
			String cookieValue = user.getMd5();
			Cookie cookie = new Cookie("t58com_action_user", cookieValue);
			cookie.setDomain(".58.com");
			cookie.setPath("/");
			cookie.setVersion(1);
			response.addCookie(cookie);
			//Session
			request.getSession().setAttribute("user", user);
			request.getSession().setAttribute("userid", user.getId());
			request.getSession().setAttribute("username", user.getUsername());
			request.getSession().setAttribute("userfunc", func);

			// 更新最后登录时间
			user.setLastlogin(DateUtil.getStringDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
			userManagerService.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			return ActionResult.view("default/login");
		}
		return ActionResult.view("default/index");
	}

	/**
	 * 左侧导航条权限组织
	 * 
	 * @return
	 */
	@Path("leftmenu")
	@GET
	@POST
	public ActionResult leftmenu() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		try {
			
			String cate1 = ServletRequestUtils.getStringParameter(request,"cate1", "");
			
			if("".equals(cate1)){
				//获取用户一级菜单展示排序
				List<String> cate1ShowList = cate1ShowList(request);
				cate1 = cate1ShowList.get(0);
			}
			
			//获取第一个一级菜单对应的拥有权限的菜单
			String func = userManagerService.getFunctionsByUser(spu.getUserByCookie(request));
			
			if (MyStore.admin.equals(func)) {//管理员验证
				func = MyStore.admin;
			}
			
			List<Menu> menuList = menuService.getListByCate1(cate1,func);
			
			//展示分类重排
			Map<String, List<Menu>> menuMap = new HashMap<String, List<Menu>>();
			
			for (Menu menu : menuList) {
				String cate2 = menu.getCate2();
				if ("".equals(cate2) || null == cate2) {
					cate2 = "no";
				}
				
				List<Menu> tempList = new ArrayList<Menu>();
				if(menuMap.containsKey(cate2)){
					tempList = menuMap.get(cate2);
				}
				tempList.add(menu);
				
				menuMap.put(cate2, tempList);
			}
			model.add("menuMap", menuMap);
			//cate2排序
			if(MyStore.cate2SortMap.containsKey(cate1)){
				model.add("cate2SortList",MyStore.cate2SortMap.get(cate1));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("default/leftmenu");
	}

	/**
	 * 头部页面
	 * 
	 * @return
	 */
	@Path("header")
	@GET
	@POST
	public ActionResult header() {
		try {
			HttpServletRequest request = beat.getRequest();
			Model model = beat.getModel();
			User user = spu.getUserByCookie(request);
			model.add("userName", user.getUsername());
			
			List<String> cate1ShowList = cate1ShowList(request);
			model.add("cate1ShowList",cate1ShowList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("default/header");
	}

	/**
	 * 底部页面
	 * 
	 * @return
	 */
	@Path("footer")
	@GET
	@POST
	public ActionResult footer() {
		return ActionResult.view("default/footer");
	}

	/**
	 * 首页欢迎页
	 * 
	 * @return
	 */
	@Path("wel")
	@GET
	@POST
	public ActionResult wel() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);
		try {
			//系统通知
			int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);
			int pageSize = ServletRequestUtils.getIntParameter(request,"pagesize", 10);
			
			Paginate<SysNotice> noticeList = NoticeService.getByPage(pageIndex, pageSize, " state = 1");

			model.add("pList",noticeList);
			model.add("noticeList",noticeList.getItems());
			model.add("pageIndex",pageIndex);
			model.add("pageSize",pageSize);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("default/wel");
	}

	/**
	 * 用户管理 show  && add
	 * 
	 * @return
	 */
	@Path("usermanager/{state}")
	@Check("usermanager/show")
	@GET
	@POST
	public ActionResult usermanager(String state) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		String returnUrl = "";

		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);

		try {
			if ("show".equals(state)) { // 用户管理页
				String username = ServletRequestUtils.getStringParameter(request, "username", "");
				String realname = ServletRequestUtils.getStringParameter(request, "realname", "");
				String department = ServletRequestUtils.getStringParameter(request, "department", "");
				int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);
				int pageSize = ServletRequestUtils.getIntParameter(request,"pagesize", 10);

				// 查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); // 查询条件
				StringBuffer url = new StringBuffer(); // 分页查询参数
				if (!"".equals(username)) {
					where.append("username?'%" + username + "%'");
					url.append("username=" + username);
					model.add("username", username);
				}
				if (!"".equals(realname)) {
					where.append(" & realname?'%" + realname + "%'");
					url.append("&realname=" + realname);
					model.add("realname", realname);
				}
				if (!"".equals(department)) {
					where.append(" & department?'%" + department + "%'");
					url.append("&department=" + department);
					model.add("department", department);
				}
				where.append(" & state=1 ");
				url.append("&state=1");
				// 以&开头时将其去之
				String condition = where.toString();
				int checkIndex = condition.indexOf("&");

				if (checkIndex < 3 && checkIndex != -1) {
					condition = condition.substring(checkIndex + 2);
				}

				String paramurl = url.toString();
				int checkIndex2 = paramurl.indexOf("&");

				if (checkIndex2 < 3 && checkIndex2 != -1) {
					paramurl = paramurl.substring(checkIndex2 + 1);
				}
				// 分页查询
				Paginate<User> userList = userManagerService.getUserByPage(
						pageIndex, pageSize, condition);
				model.add("userList", userList);
				model.add("paramurl", paramurl);
				returnUrl = "manager/usermanager";
			} else if ("add".equals(state)) { // 添加用户页
				// 菜单
				Map<String, List<Menu>> menuMap = menuService.getMenuMap();// 获取菜单权限map
				model.add("menuMap", menuMap);
				// 角色
				List<Role> roleList = roleManagerService.getAllRoles(); // 所有角色列表
				HashMap<Integer, String> roleMap = new HashMap<Integer, String>();
				for (Role r : roleList) {
					List<RolePriviledge> rolePrivs = rolePriviledgeService.getPriviledgeByRoleid(r.getId());
					String functions = "";
					for (RolePriviledge pri : rolePrivs) {
						functions = functions + "," + pri.getMenuid();
					}
					roleMap.put(r.getId(), functions);
				}
				model.add("roleList", roleList);
				model.add("roleMap", roleMap);

				// 数据操作细粒度权限列表
				TreeMap<String, List<OperMenu>> operMenuMap = UserOperService.getAllOpersMap();
				model.add("operMenuMap", operMenuMap);

				
				//角色操作权限Map
				HashMap<Integer, String> roleOperMap = new HashMap<Integer, String>();
				if (roleList != null){
					for (Role r : roleList) {
						HashSet<Long> roleOperPrivs = UserOperService.getRoleOpers(r.getId());
						String opers = "";
						for (Long operId : roleOperPrivs) {
							opers = opers + "," + operId;
						}
						roleOperMap.put(r.getId(), opers);
					}
				}
				model.add("roleOperMap", roleOperMap);
				
				returnUrl = "manager/adduser";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ActionResult.view(returnUrl);
	}

	/**
	 * 角色管理 show &&  add
	 * 
	 * @return
	 */
	@Path("rolemanager/{state}")
	@Check("rolemanager/show")
	@GET
	@POST
	public ActionResult rolemanager(String state) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		String returnUrl = "";
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);
		try {
			if ("show".equals(state)) { // 用户管理页
				String rolename = ServletRequestUtils.getStringParameter(request, "rolename", "");
				int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);
				int pageSize = ServletRequestUtils.getIntParameter(request,"pagesize", 10);

				// 查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); // 查询条件
				StringBuffer url = new StringBuffer(); // 分页查询参数
				if (!"".equals(rolename)) {
					where.append("rolename?'%" + rolename + "%'");
					url.append("rolename=" + rolename);
					model.add("rolename", rolename);
				}
				where.append(" & state=1 ");
				url.append("&state=1");
				// 以&开头时将其去之
				String condition = where.toString();
				int checkIndex = condition.indexOf("&");

				if (checkIndex < 3 && checkIndex != -1) {
					condition = condition.substring(checkIndex + 2);
				}

				String paramurl = url.toString();
				int checkIndex2 = paramurl.indexOf("&");

				if (checkIndex2 < 3 && checkIndex2 != -1) {
					paramurl = paramurl.substring(checkIndex2 + 1);
				}
				// 分页查询
				Paginate<Role> roleList = roleManagerService.getRoleByPage(pageIndex, pageSize, condition);

				model.add("roleList", roleList);
				model.add("paramurl", paramurl);
				returnUrl = "manager/rolemanager";
			} else if ("add".equals(state)) { // 添加角色页
				// 添加角色页
				Map<String, List<Menu>> menuMap = menuService.getMenuMap();// 获取权限map
				model.add("menuMap", menuMap);

				// 数据操作细粒度权限列表
				TreeMap<String, List<OperMenu>> operMenuMap = UserOperService.getAllOpersMap();
				model.add("operMenuMap", operMenuMap);

				returnUrl = "manager/addrole";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ActionResult.view(returnUrl);
	}

	/**
	 * 数据库权限管理
	 * 
	 * @return
	 */
	@Path("dbmanager/{state}")
	@Check("usermanager/show")
	@GET
	@POST
	public ActionResult dbmanager(String state) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		String returnUrl = "";
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);
		String username = ServletRequestUtils.getStringParameter(request,"username", "");
		String password = ServletRequestUtils.getStringParameter(request,"password", "");
		String hostname = ServletRequestUtils.getStringParameter(request,"hostname", "").trim();
		String dbname = ServletRequestUtils.getStringParameter(request,"dbname", "").trim();
		String tablename = ServletRequestUtils.getStringParameter(request,"tablename", "").trim();
		String priviledges = ServletRequestUtils.getStringParameter(request,"priv", "").trim();
		returnUrl = "manager/dbmanager";
		DBUser user = null;
		try {
			user = dbService.getUserByName(username);
			if (priviledges.startsWith(","))
				priviledges = priviledges.substring(1);
			if (user != null) {
				model.add("hasUser", true);
				model.add("password", user.getPassword());
			} else
				model.add("hasUser", false);
			if ("show".equals(state)) { // 数据库权限管理页
				returnUrl = "manager/dbmanager";
			} else if ("add".equals(state)) { // 添加数据库权限
				String hasUser = ServletRequestUtils.getStringParameter(request, "hasUser", "false");
				if ("false".equals(hasUser)) {
					DBUser newuser = new DBUser();
					newuser.setUsername(username);
					newuser.setPassword(password);
					newuser.setState(1);
					boolean result = dbService.saveUser(newuser);
					if (!result){
						model.add("message", "添加失败!");
					}
				}
				user = dbService.getUserByName(username);
				model.add("hasUser", true);
				model.add("password", user.getPassword());
				if (priviledges.length() > 0 && !"".equals(hostname)&& !"".equals(dbname) && !"".equals(tablename))
					dbService.saveDBPriv(username, user.getPassword(),hostname, dbname, tablename, priviledges);
			} else if ("del".equals(state) || "toedit".equals(state)) { // 删除或编辑
				if (priviledges.length() > 0 && !"".equals(hostname)&& !"".equals(dbname) && !"".equals(tablename)) {
					if ("del".equals(state)) {
						dbService.delDBPriv(username, hostname, dbname,tablename, priviledges);
					} else if ("toedit".equals(state)) {
						model.add("hostname", hostname);
						model.add("dbname", dbname);
						model.add("tablename", tablename);
						model.add("oldpriv", priviledges);
						returnUrl = "manager/editdbpriv";
					}
				}
			} else if ("update".equals(state)) {
				String oldpriv = ServletRequestUtils.getStringParameter(request, "oldpriv", "");
				if (!"".equals(hostname) && !"".equals(dbname)&& !"".equals(tablename)) {
					if (priviledges.length() == 0) {
						dbService.delDBPriv(username, hostname, dbname,tablename, oldpriv);
					} else if (!priviledges.equals(oldpriv)) {
						dbService.updateDBPri(username, user.getPassword(),hostname, dbname, tablename, priviledges);
					}
				}
			}

			model.add("username", username);

			if (returnUrl.equals("manager/dbmanager")) {
				int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);
				int pageSize = ServletRequestUtils.getIntParameter(request,"pagesize", 10);

				String searchHost = ServletRequestUtils.getStringParameter(request, "searchHost", "");
				String searchDBName = ServletRequestUtils.getStringParameter(request, "searchDBName", "");
				String searchTname = ServletRequestUtils.getStringParameter(request, "searchTname", "");
				// 查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); // 查询条件
				StringBuffer url = new StringBuffer(); // 分页查询参数

				if (!"".equals(username)) {
					where.append("username?'%" + username + "%'");
					url.append("username=" + username);
				}
				if (!"".equals(searchHost)) {
					where.append(" & hostname?'%" + searchHost + "%'");
					url.append("searchHost=" + searchHost);
					model.add("searchHost", searchHost);
				}
				if (!"".equals(searchDBName)) {
					where.append(" & dbname?'%" + searchDBName + "%'");
					url.append("&searchDBName=" + searchDBName);
					model.add("searchDBName", searchDBName);
				}
				if (!"".equals(searchTname)) {
					where.append(" & tablename?'%" + searchTname + "%'");
					url.append("&searchTname=" + searchTname);
					model.add("searchTname", searchTname);
				}
				// 以&开头时将其去之
				String condition = where.toString();
				int checkIndex = condition.indexOf("&");

				if (checkIndex < 3 && checkIndex != -1) {
					condition = condition.substring(checkIndex + 2);
				}

				String paramurl = url.toString();
				int checkIndex2 = paramurl.indexOf("&");

				if (checkIndex2 < 3 && checkIndex2 != -1) {
					paramurl = paramurl.substring(checkIndex2 + 1);
				}
				// 分页查询
				Paginate<DBPriviledge> dbPriList = dbService.getDBPrivByPage(pageIndex, pageSize, condition);
				List<DBHostPwd> hostList = dbService.getAllHost();
				model.add("dbHostList", hostList);
				model.add("privList", dbPriList);
				model.add("paramurl", paramurl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view(returnUrl);
	}

	/**
	 * 添加角色及权限
	 * 
	 * @return
	 */
	@Path("rolemanager/toaddrole")
	@Check("rolemanager/show")
	@POST
	public ActionResult addrole() {
		HttpServletRequest request = beat.getRequest();
		String flag = "failed";
		String roleName = request.getParameter("rolename");
		Role has = null;
		try {
			has = roleManagerService.getRoleByName(roleName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (null != has) {
			flag = "has";
		} else {
			try {
				String functions = request.getParameter("functions");// 菜单权限
				String opers = ServletRequestUtils.getStringParameter(request,"opers", ""); // 操作权限

				Role role = new Role();
				role.setRolename(roleName);
				role.setCreatetime(new Date());
				role.setState(1);
				if (rolePriviledgeService.saveRoleFunctions(functions, role,opers)) {
					flag = "success";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new ContentResult(flag);
	}

	/**
	 * 添加用户及权限
	 * 
	 * @return
	 */
	@Path("usermanager/toadduser")
	@Check("usermanager/show")
	@POST
	public ActionResult adduser() {
		HttpServletRequest request = beat.getRequest();
		String flag = "failed";
		String userName = request.getParameter("username");
		User has = null;
		try {
			has = userManagerService.getUserByName(userName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (null != has) {
			flag = "has";
		} else {
			try {
				String realname = request.getParameter("realname");
				String department = request.getParameter("department");
				String functions = request.getParameter("functions");
				String roleids = ServletRequestUtils.getStringParameter(request, "roles", "");
				String opers = ServletRequestUtils.getStringParameter(request,"opers", "");
				log.info("角色" + roleids + "\n权限" + functions);
				User user = new User();
				user.setUsername(userName);
				user.setRealname(realname);
				user.setDepartment(department);
				user.setFunction("");
				user.setCreatetime(new Date());
				User creatUser = spu.getUserByCookie(request);
				user.setCreateid(creatUser.getId());
				user.setState(1);

				if (userManagerService.saveUserRole(user, roleids, functions,opers)) {
					flag = "success";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return new ContentResult(flag);
	}

	/**
	 * 删除角色
	 * 
	 * @return
	 */
	@Path("rolemanager/delrole")
	@Check("rolemanager/show")
	@GET
	public ActionResult delrole() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			Role role = roleManagerService.getRoleById(id);
			role.setState(0);
			if (roleManagerService.updateRole(role)) {
				model.add("message", "删除成功!");
			} else {
				model.add("message", "删除失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.redirectContext("/rolemanager/show");
	}

	/**
	 * 删除用户
	 * 
	 * @return
	 */
	@Path("usermanager/deluser")
	@Check("usermanager/show")
	@GET
	public ActionResult deluser() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			User user = userManagerService.getUserById(id);
			user.setState(0);
			if (userManagerService.updateUser(user)&& dbService.delDBPriByUname(user.getUsername() + "_ro")) {
				model.add("message", "删除成功!");
			} else {
				model.add("message", "删除失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.redirectContext("/usermanager/show");
	}

	/**
	 * 编辑用户页面
	 * 
	 * @return
	 */
	@Path("usermanager/edituser")
	@Check("usermanager/show")
	@GET
	public ActionResult edituser() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);

		try {
			int id = Integer.parseInt(request.getParameter("id").toString());
			User user = userManagerService.getUserById(id);
			model.add("id", id);
			model.add("user", user);
			
			//用户拥有的角色
			List<UserRole> userRoles = userRoleService.getByUserid(id);
			String checkedRoles = "";
			if (userRoles != null){
				for (UserRole ur : userRoles) {
					checkedRoles += "," + ur.getRoleid();
				}
			}
			model.add("checkedRoles", checkedRoles);

			//所有角色列表
			List<Role> roleList = roleManagerService.getAllRoles();
			
			//角色菜单权限
			HashMap<Integer, String> roleMap = new HashMap<Integer, String>();
			if (roleList != null){
				for (Role r : roleList) {
					List<RolePriviledge> rolePrivs = rolePriviledgeService.getPriviledgeByRoleid(r.getId());
					String functions = "";
					for (RolePriviledge pri : rolePrivs) {
						functions = functions + "," + pri.getMenuid();
					}
					roleMap.put(r.getId(), functions);
				}
			}
			model.add("roleList", roleList);
			model.add("roleMap", roleMap);

			//获取菜单权限map
			Map<String, List<Menu>> menuMap = menuService.getMenuMap();
			List<Menu> menuList = menuService.getAllMenu(); // 获取所有权限节点列表
			model.add("menuMap", menuMap);

			//用户菜单权限
			String userfunction = userManagerService.getNewAndOldUserFunc(user, menuList);
			model.add("userfunction", userfunction);

			// 数据操作细粒度权限列表
			TreeMap<String, List<OperMenu>> operMenuMap = UserOperService.getAllOpersMap();
			model.add("operMenuMap", operMenuMap);

			// 用户操作权限
			HashSet<Long> opersSet = UserOperService.getUserOpers(user.getId());
			StringBuffer useropers = new StringBuffer();
			for (Long operId : opersSet) {
				useropers.append("," + operId );
			}

			if (useropers.length() > 0) {
				model.add("useropers",useropers.toString());
			} else {
				model.add("useropers", "");
			}

			//角色操作权限Map
			HashMap<Integer, String> roleOperMap = new HashMap<Integer, String>();
			if (roleList != null){
				for (Role r : roleList) {
					HashSet<Long> roleOperPrivs = UserOperService.getRoleOpers(r.getId());
					String opers = "";
					for (Long operId : roleOperPrivs) {
						opers = opers + "," + operId;
					}
					roleOperMap.put(r.getId(), opers);
				}
			}
			model.add("roleOperMap", roleOperMap);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("manager/edituser");
	}

	/**
	 * 编辑角色页面
	 * 
	 * @return
	 */
	@Path("rolemanager/editrole")
	@Check("rolemanager/show")
	@GET
	public ActionResult editrole() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);

		try {
			int id = Integer.parseInt(request.getParameter("id").toString());
			Role role = roleManagerService.getRoleById(id);
			model.add("role", role);
			List<RolePriviledge> rolePrivs = rolePriviledgeService.getPriviledgeByRoleid(id);
			String functions = "";
			if (rolePrivs != null){
				for (RolePriviledge pri : rolePrivs) {
					functions = functions + "," + pri.getMenuid();
				}
			}
				
			model.add("rolefunction", functions);

			Map<String, List<Menu>> menuMap = menuService.getMenuMap();// 获取权限map
			model.add("menuMap", menuMap);
			
			
			//数据操作细粒度权限列表
			TreeMap<String, List<OperMenu>> operMenuMap = UserOperService.getAllOpersMap();
			model.add("operMenuMap", operMenuMap);

			//角色操作权限
			HashSet<Long> opersSet = UserOperService.getRoleOpers(id);
			StringBuffer useropers = new StringBuffer();
			for (Long operId : opersSet) {
				useropers.append("," +operId);
			}

			if (useropers.length() > 0) {
				model.add("roleopers",useropers.toString());
			} else {
				model.add("roleopers", "");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("manager/editrole");
	}

	/**
	 * 更新角色编辑信息
	 * 
	 * @return
	 */
	@Path("rolemanager/toeditrole")
	@Check("rolemanager/show")
	@POST
	public ActionResult toeditrole() {
		HttpServletRequest request = beat.getRequest();
		String flag = "failed";
		try {
			int id = Integer.parseInt(request.getParameter("id").toString());
			String rolename = request.getParameter("rolename");
			String function = request.getParameter("functions");
			String oldfunctions = request.getParameter("oldfunctions");
			
			String opers =  ServletRequestUtils.getStringParameter(request,"opers", "");
			String oldopers =  ServletRequestUtils.getStringParameter(request,"oldopers", "");
			
			Role role = roleManagerService.getRoleById(id);
			role.setRolename(rolename);
			if(oldfunctions.equals(function) && oldopers.equals(opers)){
				return new ContentResult("success");
			}
			
			if(rolePriviledgeService.updateRoleFunctions(role, function,opers)){
				flag = "success";
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = "error";
		}
		return new ContentResult(flag);
	}

	/**
	 * 更新用户编辑信息
	 * 
	 * @return
	 */
	@Path("usermanager/toedituser")
	@Check("usermanager/show")
	@POST
	public ActionResult toedituser() {
		HttpServletRequest request = beat.getRequest();
		String flag = "failed";
		String oldFuncs = "", oldRoles = "", oldOpers = "";
		User user = null;
		User olduser = null;
		try {
			int id = Integer.parseInt(request.getParameter("id").toString());
			String username = request.getParameter("username");
			String realname = request.getParameter("realname");
			String department = request.getParameter("department");
			String function = request.getParameter("functions");

			user = userManagerService.getUserById(id);
			user.setUsername(username);
			user.setRealname(realname);
			user.setDepartment(department);
			user.setFunction("");
			String roleids = ServletRequestUtils.getStringParameter(request,"roles", "");
			String opers = ServletRequestUtils.getStringParameter(request,"opers", "");

			// 旧数据 BK
			oldRoles = ServletRequestUtils.getStringParameter(request,"userHasedRoles", "");
			oldFuncs = ServletRequestUtils.getStringParameter(request,"userfunction", "");
			oldOpers = ServletRequestUtils.getStringParameter(request,"oldOpers", "");
			olduser = userManagerService.getUserById(id);
			// 更新数据权限 先删除原来全部的旧数据 再重新插入
			if (userManagerService.updateUserRole(user, roleids, function,opers)){
				flag = "success";
			}
				
		} catch (Exception e) {
			e.printStackTrace();
			try {
				userManagerService.updateUserRole(olduser, oldRoles, oldFuncs,oldOpers);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			flag = "error";
		}

		return new ContentResult(flag);

	}


	/**
	 * 用户报表邮件订阅管理
	 * 
	 * @return
	 */
	@SuppressWarnings("finally")
	@Path("submailmanager/{state}")
	@Check("submailmanager/show")
	@GET
	@POST
	public ActionResult subMailManager(String state) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		String returnUrl = "";
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);
		try {
			if ("show".equals(state)) { // 用户管理页
				String subName = ServletRequestUtils.getStringParameter(request, "subName", "");
				String reportName = ServletRequestUtils.getStringParameter(request, "reportName", "");
				int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);

				// 查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); // 查询条件
				StringBuffer paramurl = new StringBuffer(); // 分页查询参数

				int userId = (int) spu.getUserByCookie(request).getId();
				where.append(" userId=" + userId);
				if (!"".equals(subName)) {
					where.append(" & subName?'%" + subName + "%'");
					paramurl.append("&subName=" + subName);
				}
				if (!"".equals(reportName)) {
					where.append(" & reportName?'%" + reportName + "%'");
					paramurl.append("&reportName=" + reportName);
				}
				// 分页查询
				Paginate<IRSubMailVo> subMailList = iRSubMailService
						.getSubListByPage(pageIndex, 20, where.toString());
				model.add("rsList", subMailList.getItems());
				model.add("subMailList", subMailList);
				model.add("paramurl", paramurl);
				model.add("subName", subName);
				model.add("reportName", reportName);
				returnUrl = "manager/submailmanager";
			} else if ("edit".equals(state)) { // 修改用户页
				int id = ServletRequestUtils.getIntParameter(request, "id", 0);
				IRSubMailVo vo = iRSubMailService.findOneById(id);
				model.add("vo", vo);
				returnUrl = "manager/editsubmail";
			} else if ("updateedit".equals(state)) { // 更新编辑订阅信息
				String result = "error";
				try {
					int id = ServletRequestUtils.getIntParameter(request, "id",0);
					String sendEmail = ServletRequestUtils.getStringParameter(request, "sendEmail", "");
					String sendFre = ServletRequestUtils.getStringParameter(request, "sendFre", "");
					String subName = ServletRequestUtils.getStringParameter(request, "subName", "");

					// 后端邮箱校验
					for (String ad : sendEmail.split("/")) {
						ad = ad.trim();
						if(!(ad.endsWith("@58.com")||ad.endsWith("@58ganji.com")||ad.endsWith("@zhiyou.ganji.com")||ad.endsWith("@ganji.com")||ad.endsWith("@doumi.com"))){
							return new ContentResult(result);
						}
					}

					if (id > 0 && !"".equals(sendEmail) && !"".equals(sendFre)&& !"".equals(subName)) {
						IRSubMailVo vo = iRSubMailService.findOneById(id);
						if (null != vo) {
							vo.setSendEmail(sendEmail);
							vo.setSendFre(sendFre);
							vo.setSubName(subName);

							int end = iRSubMailService.updateVo(vo);
							if (end > 0) {
								result = "success";
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					return new ContentResult(result);
				}

			} else if ("changestate".equals(state)) { // 状态修改
				String result = "error";
				try {
					int id = ServletRequestUtils.getIntParameter(request, "id",0);
					int upstate = ServletRequestUtils.getIntParameter(request,"upstate", -1);
					if (id > 0 && upstate > -1) {
						IRSubMailVo vo = iRSubMailService.findOneById(id);
						if (null != vo) {
							vo.setState(upstate);
							int end = iRSubMailService.updateVo(vo);
							if (end > 0) {
								result = "success";
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					return new ContentResult(result);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ActionResult.view(returnUrl);
	}
	/**
	 * 用户报表大数据量下载管理
	 * 
	 * @return
	 */
	@Check("userdownmanager")
	@GET
	@POST
	public ActionResult userdownmanager() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		String returnUrl = "";
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class,model);
		try {
			 // 用户管理页
				String subName = ServletRequestUtils.getStringParameter(request, "DownsubName", "");
				String reportName = ServletRequestUtils.getStringParameter(request, "reportName", "");
				int pageIndex = ServletRequestUtils.getIntParameter(request,"pageindex", 0);

				// 查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); // 查询条件
				StringBuffer paramurl = new StringBuffer(); // 分页查询参数

				int userId = (int) spu.getUserByCookie(request).getId();
				where.append(" userId=" + userId);
				if (!"".equals(subName)) {
					where.append(" & subName?'%" + subName + "%'");
					paramurl.append("&subName=" + subName);
				}
				if (!"".equals(reportName)) {
					where.append(" & reportName?'%" + reportName + "%'");
					paramurl.append("&reportName=" + reportName);
				}
				// 分页查询
				Paginate<UserSubMailVo> subDownList = UserDownService
						.getSubListByPage(pageIndex, 20, where.toString());
				model.add("rsList", subDownList.getItems());
				model.add("subMailList", subDownList);
				model.add("paramurl", paramurl);
				model.add("subName", subName);
				model.add("reportName", reportName);
				returnUrl = "manager/userdownmanager";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ActionResult.view(returnUrl);
	}
	private String[] excludeCate = { "个人中心", "细粒度权限( 暂)", "精准数据细粒度"};
	private String[] excludeCate2 = { "来源","来源管理","分析报告" };
	private String[] excludeMenuNames = {};


	/**
	 * 数据菜单列表概要
	 * 
	 * @return
	 */
	@Path("manager/menulist")
	@POST
	@GET
	public ActionResult showMenuList() {
		Set<String> excludeSet = new HashSet<String>();
		Set<String> excludeSet2 = new HashSet<String>();
		Set<String> excludeSet3 = new HashSet<String>();
		
		Collections.addAll(excludeSet, excludeCate);
		Collections.addAll(excludeSet2, excludeCate2);
		Collections.addAll(excludeSet3, excludeMenuNames);

		Model model = beat.getModel();
		try {
			List<Menu> menuList = new ArrayList<Menu>();
			menuList = menuService.getAllMenu();
			// 重新组织权限列表，便于页面遍历展示
			TreeMap<String, Map<String, List<Menu>>> menuMap = new TreeMap<String, Map<String, List<Menu>>>();
			for (Menu menu : menuList) {
				String cate1 = menu.getCate1();
				String cate2 = menu.getCate2();
				String menuName = menu.getName();
				
				if (excludeSet.contains(cate1) || excludeSet2.contains(cate2) || excludeSet3.contains(menuName)) {
					continue;
				}

				if ("".equals(cate2) || null == cate2) {
					cate2 = "no";
				}

				Map<String, List<Menu>> cate2Map = new HashMap<String, List<Menu>>();
				List<Menu> list = new ArrayList<Menu>();

				if (menuMap.containsKey(cate1)) {
					cate2Map = menuMap.get(cate1);

					if (cate2Map.containsKey(cate2)) {
						list = cate2Map.get(cate2);
					}
				}
				list.add(menu);
				cate2Map.put(cate2, list);
				menuMap.put(cate1, cate2Map);
			}
			model.add("menuMap", menuMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionResult.view("default/menuList");
	}
	
	
	/**获取用户所有权限的一级类菜单  并核对默认顺序 将其展示
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private List<String> cate1ShowList(HttpServletRequest request) throws Exception {
		//获取用户权限
		List<Menu> menuList = new ArrayList<Menu>();
		
		String func = userManagerService.getFunctionsByUser(spu.getUserByCookie(request));
		
		if (MyStore.admin.equals(func)) {// 管理员验证
			menuList = menuService.getAllMenu();
		} else {
			menuList = menuService.getMenuListByFunctions(func);
		}
		
		//获取用户菜单大类
		TreeSet<String> cate1Set  = new TreeSet<String>();
		for (Menu menu : menuList) {
			cate1Set.add(menu.getCate1());
		}
		
		//展示排序
		List<String> cate1ShowList = new ArrayList<String>();
		for (String cate1 : MyStore.cate1SortList) {
			if(cate1Set.contains(cate1)){
				cate1ShowList.add(cate1);
			}
		}
		
		return cate1ShowList;
	}
}
